package com.geek.project.geekauthstarter.service.impl;

import com.geek.project.geekauthstarter.props.JwtProperties;
import com.geek.project.geekauthstarter.service.JwtService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Map;

/**
 * JwtService实现类
 *
 * @author geek
 */
public class JwtServiceImpl implements JwtService {

    private JwtProperties jwtProperties;

    public JwtServiceImpl(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public String generateToken(Map<String, Object> map, int expireMinutes) {
        PrivateKey key = jwtProperties.getPrivateKey();
        return Jwts.builder()
                .setClaims(map)
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(key, SignatureAlgorithm.RS256)
                .compact();
    }

    @Override
    public String generateToken(Map<String, Object> map) {
        return this.generateToken(map, jwtProperties.getExpire());
    }

    @Override
    public Jws<Claims> parserToken(String token) {
        PublicKey key = jwtProperties.getPublicKey();
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
    }

    @Override
    public Map<String, Object> getInfoFromToken(String token) {
        PublicKey key = jwtProperties.getPublicKey();
        Jws<Claims> claimsJws = parserToken(token);
        return claimsJws.getBody();
    }
}
